$().ready(function(){
    // 事件绑定
    InitPageEvent();
    // 页面初始化
    InitPageInfo();
    
});


/**
 * 事件绑定
 */
function InitPageEvent(){
    // 重置按钮事件绑定
    $(".resetBtn").click(function(){
        $("#partybuildingEditor").resetForm();
        return false;
    }).easyconfirm({
        locale: {
            title: '操作确认',
            button: ['取消', '是的，确定重置']
        }
    });
    
    // 保存按钮事件绑定
    $(".saveBtn").click(function(){
        $("#partybuildingEditor").submit();
        return false;
    })
    
    
    //删除按钮事件绑定
    $(".delFile").bind("click", delFileClickHandler).easyconfirm({
        locale: {
            title: '操作确认',
            text: '您确定要删除附件？',
            button: ['取消', '是的，确定删除']
        }
    });
    
    // 日期按钮事件绑定
    $("#postdate").datepicker({
        dateFormat: 'yy-mm-dd'
    }).attr("readonly", true);
}



/**
 * 页面信息初始化
 */
function InitPageInfo(){
    loadUploadBtn();
    /**  表单提交 **/
    // 中文字两个字节       
    jQuery.validator.addMethod("byteRangeLength", function(value, element, param){
        var length = value.length;
        for (var i = 0; i < value.length; i++) {
            if (value.charCodeAt(i) > 127) {
                length++;
            }
        }
        return this.optional(element) ||
        (length >= param[0] && length <= param[1]);
    }, "请确保输入的值在3-15个字节之间(一个中文字算2个字节)");
    jQuery.validator.addMethod("isDate", function(value, element){
        var ereg = /^(\d{1,4})(-|\/)(\d{1,2})(-|\/)(\d{1,2})$/;
        var r = value.match(ereg);
        if (r == null) {
            return false;
        }
        var d = new Date(r[1], r[3] - 1, r[5]);
        var result = (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[5]);
        return this.optional(element) || (result);
    }, "请输入正确的日期");
    
    $("#partybuildingEditor").validate({
        submitHandler: function(form){
            var tmpMainphoto = "";
            if ($("input[name='mainphoto']:checked").val() !== undefined) {
                tmpMainphoto = $("input[name='mainphoto']:checked").val();
            };
            
            $(form).ajaxSubmit({
                target: "#article-msg",
                data: {
                    mainphoto: tmpMainphoto
                },
                dataType: "json",
                beforeSubmit: function(){
                    $(".loadingbox").append(loadingTpl, {
                        icoType: 'clear',
                        loadIcon: '<img src=\"images/loading002.gif\">',
                        msgHtml: '正在提交数据，请稍候...'
                    });
                    $(".loading").fadeIn(50);
                },
                success: function(data){
                    if (!data.success) {
                        $(".loadingbox").empty();
                        $(".loadingbox").append(loadingTpl, {
                            icoType: 'fail',
                            loadIcon: '',
                            msgHtml: data.message
                        });
                        $(".loadingbox").delay(3000).fadeOut(600);
                    }
                    else {
                        $(".loadingbox").empty();
                        $(".loadingbox").append(loadingTpl, {
                            icoType: "succ",
                            loadIcon: "",
                            msgHtml: data.message
                        });
                        $(".loadingbox").fadeIn(50);
                        $(".loadingbox").delay(2000).fadeOut(600);
                    }
                    
                }
            });
        },
        rules: {
            title: {
                required: true,
                byteRangeLength: [4, 200]
            },
            
            
            postdate: {
                required: true,
                isDate: true
            },
            content: {
                required: true
            }
        },
        messages: {
            title: {
                required: "请填写标题",
                byteRangeLength: "标题必须在4-200个字符之间(一个中文字算2个字符)"
            },
            
            
            postdate: {
                required: "请填写电子台账发布日期",
                isDate: "文章发布日期格式错误"
            },
            content: {
                required: "说明内容必须填写"
            }
        }
    });
}


/**
 *
 * 上传文件
 */
function loadUploadBtn(){
    var uploader = '../js-plugin/uploadify/uploadify_cn.swf';
    var files_script = "/action/master/ArticleFileUpload";
    var cancelImg = '../js-plugin/uploadify/cancel.png';
    var folder = '/upload';
    var identifies = {
        'identifies': $("#identifies").val()
    };
    
    $('#pdf_file').uploadify({
        'uploader': uploader,
        'script': files_script,
        'scriptData': identifies,//解决firefox 的session bug
        'cancelImg': cancelImg,
        'folder': folder,
        'width': 110,
        'auto': true,
        'multi': true,
        'fileExt': '*.pdf',
        'fileDesc': '请选择PDF文件 ( .PDF)',
        'queueID': 'custom-queue',
        'buttonText': "选择PDF文件",
        'removeCompleted': true,
        'onComplete': function(e, queueId, fileObj, response, data){
            var obj = $.parseJSON(response);
            if (obj.success) {
                $(".loadingbox").empty();
                $(".loadingbox").append(loadingTpl, {
                    icoType: "succ",
                    loadIcon: "",
                    msgHtml: fileObj.name + " 上传成功"
                });
                $(".loadingbox").fadeIn(50);
                $(".loadingbox").delay(2000).fadeOut(600);
                
                $(".attachment").show();
                var templateTr = $("#attachment-preview-tpl").children("li").clone(true).show();
                templateTr.find("a").attr("href", obj.fileid);
                templateTr.find("a").click(delFileClickHandler).easyconfirm({
                    locale: {
                        title: '操作确认',
                        button: ['取消', '是的，确定删除']
                    }
                });
                templateTr.find("b").text(obj.originalnames);
                $('#attachment-preview').append(templateTr);
                
            }
            else {
                $(".loadingbox").empty();
                $(".loadingbox").append(loadingTpl, {
                    icoType: 'fail',
                    loadIcon: '',
                    msgHtml: obj.message
                });
                $(".loadingbox").delay(3000).fadeOut(600);
                
                $('#status-message').append("<li>" + obj.message + "</li>");
            }
        }
    });
}

var delFileClickHandler = function(e){
    e.preventDefault();
    var tmp = $(e.currentTarget);
    var tmpid = tmp.attr("href");
    $.post("/action/master/deleteArticleFile", {
        Action: "post",
        id: tmpid
    }, function(data, textStatus){
        if (!data.success) {
            $(".loadingbox").empty();
            $(".loadingbox").append(loadingTpl, {
                icoType: 'fail',
                loadIcon: '',
                //        msgHtml: obj.message
            });
            $(".loadingbox").delay(3000).fadeOut(600);
        }
        else {
            $(".loadingbox").empty();
            $(".loadingbox").append(loadingTpl, {
                icoType: "succ",
                loadIcon: "",
                msgHtml: data.message
            });
            $(".loadingbox").fadeIn(50);
            $(".loadingbox").delay(2000).fadeOut(600);
            tmp.parents("li").hide("slide", {
                direction: "left"
            }, 1000).delay(1000).remove();
            //			tmp.parents("li").hide(2000, function(){
            //                    tmp.parents("li").remove();
            //                });
        }
    }, "json");
};



